using System;
using log4net;
using WcfTest.GuiClient.Properties;
using WcfTest.GuiClient.Services;
using WcfTest.GuiClient.Services.Impl;
using WcfTest.GuiClient.Views;

namespace WcfTest.GuiClient.Presenters
{
	internal class MainPresenter
	{
		#region Fields

		private readonly ILog log = LogManager.GetLogger(typeof(MainPresenter));
		private readonly IMainView view;

		private ITalkingService talkingService;
		private bool recreateTalkingService;

		#endregion Fields

		#region Properties

		private ITalkingService TalkingService
		{
			get
			{
				if (talkingService == null || recreateTalkingService)
				{
					recreateTalkingService = false;
					talkingService = new TalkingService(view.TalkingServiceUrl);
				}

				return talkingService;
			}
		}

		#endregion Properties

		#region Constructors

		public MainPresenter(IMainView view)
		{
			this.view = view;
		}

		#endregion Constructors

		#region Methods

		public void OnLoad()
		{
			view.TalkingServiceUrl = Settings.Default.TalkingServiceUrl;
		}

		public void OnClosing()
		{
			Settings.Default.TalkingServiceUrl = view.TalkingServiceUrl;
			Settings.Default.Save();
		}

		public void OnSayButtonClick()
		{
			view.EnterWaitMode();
			TalkingService.BeginSaying(SaySuccessCallback, ServiceErrorCallback);
		}
		
		public void OnTalkingServiceUrlChanged()
		{
			recreateTalkingService = true;
		}

		#endregion Methods

		#region Service callbacks

		private void SaySuccessCallback(string response)
		{
			view.EnterNormalMode();

			var message = string.Format("The service said: '{0}'", response);
			LogInfo(message);
		}

		private void ServiceErrorCallback(Exception e)
		{
			view.EnterNormalMode();

			log.Error(e);
			view.LogError(e.Message);
		}

		#endregion Service callbacks

		#region Helpers

		private void LogInfo(string message)
		{
			view.Log(message);
			log.Info(message);
		}

		#endregion Helpers
	}
}